angular.module('http-interceptor', ['constants', 'app-util-func', 'ngStorage', 'ionic'])

.run ($rootScope, $ionicLoading) ->
    $rootScope.showLoading = -> $ionicLoading.show()
    $rootScope.hideLoading = -> $ionicLoading.hide()

.config ($provide, $httpProvider, backend, inWeixin, $localStorageProvider) ->
    if backend
        httpDecorator = ($delegate)->
            return  (method, url, post, callback, headers, timeout, withCredentials) ->
                if url != null && url != undefined && url.charAt(0) == '/'
                    if url != '/customer/login' and url != '/customer/register'
                        # 对于非登录/注册的接口，访问时加上用户token
                        token = $localStorageProvider.get 'token'
                        if token != null
                            if url.indexOf('?') < 0 then url = url + "?token=#{token}"
                            else url = url + "&token=#{token}"
                    url = backend + url
                $delegate(method, url, post, callback, headers, timeout, withCredentials)
        $provide.decorator('$httpBackend', ["$delegate", httpDecorator])
    if inWeixin # 如果是微信，使用浏览器提供的后退功能
        $provide.decorator '$ionicHistory', ($delegate) ->
            $delegate.goBack = (i) ->
                if i != undefined
                    window.history.go i
                else
                    window.history.back()
            $delegate
    $httpProvider.interceptors.push ($q, $rootScope) ->
        request: (config) ->
            if config.loadingAnimation != false
                $rootScope.showLoading()
            config
        response: (response) ->
            if response.config?.loadingAnimation != false
                $rootScope.hideLoading()
            response
        responseError: (rejection) ->
            if rejection.config?.loadingAnimation != false
                $rootScope.hideLoading()
            $q.reject rejection